<template>
  <div class="map-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button-group>
        <el-button @click="showAddLayerDialog = true" type="primary">
          <el-icon><Plus /></el-icon>
          添加图层
        </el-button>
        <el-button @click="clearAllLayers">
          <el-icon><Delete /></el-icon>
          清空图层
        </el-button>
        <el-button @click="resetView">
          <el-icon><Refresh /></el-icon>
          复位视角
        </el-button>
      </el-button-group>
    </div>

    <!-- 图层树面板 -->
    <div class="layer-panel" :class="{ collapsed: panelCollapsed }">
      <div class="panel-header">
        <span>图层管理</span>
        <el-button
          text
          @click="panelCollapsed = !panelCollapsed"
          class="collapse-btn"
        >
          <el-icon>
            <component :is="panelCollapsed ? 'ArrowRight' : 'ArrowLeft'" />
          </el-icon>
        </el-button>
      </div>

      <div class="panel-content" v-if="!panelCollapsed">
        <LayerTree />
      </div>
    </div>

    <!-- 地图容器 -->
    <div id="mars3dContainer" class="mars3d-container"></div>

    <!-- 添加图层对话框 -->
    <AddLayerDialog v-model:visible="showAddLayerDialog" />

    <!-- 状态栏 -->
    <div class="status-bar">
      <span>图层数量: {{ layerStore.layers.length }}</span>
      <span>Mars3D版本: 3.6.0</span>
    </div>
  </div>
</template>

<script setup>
/* global mars3d, Cesium */
import { ref, onMounted, onUnmounted } from 'vue'
import { Plus, Delete, Refresh, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 关键：引入 mars3d
import * as mars3d from "mars3d"
import { useLayerStore } from '../stores/layerStore'
import LayerTree from '../components/LayerTree.vue'
import AddLayerDialog from '../components/AddLayerDialog.vue'

const layerStore = useLayerStore()
const showAddLayerDialog = ref(false)
const panelCollapsed = ref(false)
let map = null

onMounted(() => {
  initMap()

  // 监听Electron文件打开事件
  if (window.require) {
    const { ipcRenderer } = window.require('electron')
    ipcRenderer.on('file-opened', (event, filePath) => {
      loadFileAsGeoJSON(filePath)
    })
  }
})

onUnmounted(() => {
  if (map) {
    map.destroy()
    map = null
  }
})

// 初始化地图
const initMap = () => {
  // 确保 Mars3D 已加载
  if (!window.mars3d && !mars3d) {
    console.error('Mars3D 未加载，请检查库文件引入')
    return
  }

  const Mars3D = window.mars3d || mars3d

  const mapOptions = {
    scene: {
      center: { lat: 22.54, lng: 113.95, alt: 15000, heading: 348, pitch: -50 },
      showSun: true,
      showMoon: true,
      showSkyBox: true,
      showSkyAtmosphere: true,
      fog: true,
      fxaa: true,
      globe: {
        depthTestAgainstTerrain: false,
        showGroundAtmosphere: true,
        enableLighting: false
      }
    },
    control: {
      baseLayerPicker: true,
      homeButton: true,
      sceneModePicker: true,
      navigationHelpButton: true,
      fullscreenButton: true,
      geocoder: false,
      timeline: false,
      animation: false,
      vrButton: false,
      infoBox: true,
      selectionIndicator: true
    },
    terrain: {
      url: '//data.mars3d.cn/terrain'
    },
    basemaps: [
      {
        name: '天地图影像',
        icon: '//data.mars3d.cn/img/thumbnail/tianditu_img.png',
        type: 'tdt',
        layer: 'img_d',
        show: true
      },
      {
        name: '天地图矢量',
        icon: '//data.mars3d.cn/img/thumbnail/tianditu_vec.png',
        type: 'tdt',
        layer: 'vec_d'
      },
      {
        name: 'OSM',
        icon: '//data.mars3d.cn/img/thumbnail/osm.png',
        type: 'xyz',
        url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
        subdomains: ['a', 'b', 'c']
      }
    ]
  }

  try {
    map = new Mars3D.Map('mars3dContainer', mapOptions)
    console.log('Mars3D地图创建成功:', map)

    // 设置地图实例到store - 这一步很关键！
    layerStore.setMap(map)

    map.on(Mars3D.EventType.load, () => {
      console.log('Mars3D地图初始化完成')
    })

    // 添加地图点击事件
    map.on(Mars3D.EventType.click, (event) => {
      console.log('地图点击事件:', event)
    })

  } catch (error) {
    console.error('地图初始化失败:', error)
  }
}

// 清空所有图层
const clearAllLayers = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有图层吗？', '确认清空', {
      type: 'warning'
    })
    layerStore.clearLayers()
  } catch {
    // 用户取消
  }
}

// 复位视角
const resetView = () => {
  if (map) {
    map.flyToPoint(
      {
        lat: 22.54,
        lng: 113.95,
        alt: 15000,
        heading: 348,
        pitch: -50
      },
      { duration: 2 }
    )
  }
}

// 加载文件为GeoJSON
const loadFileAsGeoJSON = async (filePath) => {
  if (window.require) {
    const { ipcRenderer } = window.require('electron')
    const result = await ipcRenderer.invoke('read-file', filePath)

    if (result.success) {
      try {
        const data = JSON.parse(result.data)
        await layerStore.addLayer({
          name: filePath.split('/').pop(),
          type: 'geojson',
          data: data,
          visible: true
        })
        ElMessage.success('文件加载成功')
      } catch (error) {
        console.error('解析GeoJSON失败:', error)
        ElMessage.error('文件解析失败')
      }
    }
  }
}
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.toolbar {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  background: rgba(255, 255, 255, 0.9);
  padding: 8px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.layer-panel {
  position: absolute;
  top: 60px;
  right: 10px;
  width: 300px;
  max-height: calc(100vh - 120px);
  background: rgba(255, 255, 255, 0.95);
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  transition: all 0.3s ease;
}

.layer-panel.collapsed {
  width: 40px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #e4e7ed;
  font-weight: bold;
  font-size: 14px;
}

.collapse-btn {
  padding: 4px !important;
  min-height: auto !important;
}

.panel-content {
  padding: 12px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.mars3d-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.status-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 30px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  display: flex;
  align-items: center;
  padding: 0 12px;
  font-size: 12px;
  z-index: 1000;
}

.status-bar span {
  margin-right: 20px;
}

/* 滚动条样式 */
.panel-content::-webkit-scrollbar {
  width: 6px;
}

.panel-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.panel-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.panel-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
